<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>《JavaScript高级程序设计》- 第十五章：DOM拓展 |  欢迎</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="欢迎" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-JavaScript学习/《JavaScript高级程序设计》- 第十五章：DOM拓展"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  《JavaScript高级程序设计》- 第十五章：DOM拓展
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/02/28/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E5%8D%81%E4%BA%94%E7%AB%A0%EF%BC%9ADOM%E6%8B%93%E5%B1%95/" class="article-date">
  <time datetime="2022-02-28T03:32:22.000Z" itemprop="datePublished">2022-02-28</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaScript%E5%AD%A6%E4%B9%A0/">JavaScript学习</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">3.2k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">13 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="第十五章：DOM拓展"><a href="#第十五章：DOM拓展" class="headerlink" title="第十五章：DOM拓展"></a>第十五章：DOM拓展</h2><p>尽管DOM API已经很不错了，但是仍然不断有新的标准或专有的拓展出现，以此来支持更多的功能；W3C正在着手于指定相关的规范。</p>
<p>在此期间，诞生了几个比较受欢迎的DOM拓展：Selectors、HTML5；另外还有较小的Element Traversal规范。</p>
<h3 id="15-1-Selectors-API"><a href="#15-1-Selectors-API" class="headerlink" title="15.1 Selectors API"></a>15.1 Selectors API</h3><p>Selectors API 是 <strong>W3C推荐标准</strong>，其规定了<strong>浏览器原生支持CSS查询</strong>的API；</p>
<p>Selectors API Level 1有两个核心方法：<code>querySelector()</code>和<code>querySelectorAll()</code></p>
<p>Selectors API Level 2在Element类型上，新增了更多方法，如：<code>matches()</code>、<code>find()</code>、<code>findAll()</code>；但并未被浏览器声明许可；</p>
<blockquote>
<p>通过浏览器原生支持API，解析和遍历DOM树可以通过底层编译语言实现，使得性能有了数量级的提升</p>
</blockquote>
<h4 id="15-1-1-querySelector"><a href="#15-1-1-querySelector" class="headerlink" title="15.1.1 querySelector()"></a>15.1.1 <code>querySelector()</code></h4><p><code>querySelector()</code>方法，接收一个参数：</p>
<ul>
<li>CSS选择符</li>
</ul>
<p>返回匹配该模式的第一个后代元素；如果不匹配，返回null。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取body元素</span></span><br><span class="line"><span class="keyword">let</span> body = <span class="built_in">document</span>.querySelector(<span class="string">&#x27;body&#x27;</span>);</span><br><span class="line"><span class="comment">// 获取body元素下的类名为myClass的第一个元素</span></span><br><span class="line"><span class="keyword">let</span> myDiv = body.querSelector(<span class="string">&#x27;.myClass&#x27;</span>);</span><br><span class="line"><span class="comment">// 获取类名为button的图片</span></span><br><span class="line"><span class="keyword">let</span> img = <span class="built_in">document</span>.body.querySelector(<span class="string">&#x27;img.button&#x27;</span>);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>显然，如果在document上使用，则会从文档开始搜索；如果在元素上使用，则会在该元素的后代中开始搜索。</p>
<p>注意：如果选择符有错误，该方法则会抛出错误；</p>
</blockquote>
<h4 id="15-1-2-querySelectorAll"><a href="#15-1-2-querySelectorAll" class="headerlink" title="15.1.2 querySelectorAll()"></a>15.1.2 <code>querySelectorAll()</code></h4><p>使用和<code>querySelector()</code>一样，但是返回值有所不同：</p>
<ul>
<li>如果匹配成功，返回一个<code>NodeList</code>的静态实例；反之返回一个空的<code>NodeList</code>的静态实例。</li>
</ul>
<p><em>注意：这里的<code>NodeList</code>实例<strong>并不是”实时的”<strong>，只是当前状态下，查询到结果的一个</strong>“快照”</strong></em></p>
<blockquote>
<p>与<code>querySelector()</code>一样，也会因为选择符错误而抛出错误</p>
</blockquote>
<h3 id="15-1-3-matches"><a href="#15-1-3-matches" class="headerlink" title="15.1.3 matches()"></a>15.1.3 <code>matches()</code></h3><p><code>matches()</code>接收一个参数，用于判断<strong>是否包含</strong>带有该CSS选择符的元素。</p>
<ul>
<li>CSS选择符</li>
</ul>
<p>如果匹配，则返回true；反之，返回false。</p>
<h3 id="15-2-元素遍历"><a href="#15-2-元素遍历" class="headerlink" title="15.2 元素遍历"></a>15.2 元素遍历</h3><p>由于有些浏览器，或不同版本的浏览器，<strong>会把元素间空格当成空白节点</strong>；</p>
<p>W3C通过新的Element Traversal规范，给DOM元素定义一组新的属性：</p>
<ul>
<li><code>childElmentCount</code>，返回子元素数量（不包括文本节点和注释）；</li>
<li><code>firstElementChild</code>，指向第一个Element类型的子元素（Element版的<code>firstChild</code>）；</li>
<li><code>lastElementChild</code>， 指向最后一个Element类型的子元素（Element版<code>lastChild</code>） ；</li>
<li><code>previousElementSibling</code>， 指向前一个Element类型的同胞元素（Element版<code>previousSibling</code>） ；</li>
<li><code>nextElementSibling</code>， 指向后一个Element类型的同胞元素（Element版<code>nextSibling</code>） 。  </li>
</ul>
<blockquote>
<p>如果不适用Element Traversal规范，遍历子元素的话，可以这样做：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> parentElement = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;parent&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> currentChildNode = parentElement.firstChild;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 一直遍历子元素，直至为null</span></span><br><span class="line"><span class="keyword">while</span>( currentChildNode ) &#123;</span><br><span class="line">    <span class="keyword">if</span>( currentChildNode.nodeType === <span class="number">1</span>)&#123; <span class="comment">// 判断是否为Element类型</span></span><br><span class="line">        <span class="comment">// 若果是，则进行元素操作</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>( currentChildNode === parentElement.lastChild ) &#123;	<span class="comment">// 如果是最后一个元素，就退出遍历</span></span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    currentChildNode = currentChildNode.nextSibling;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<blockquote>
<p>可以使用Element Traversal规范改写</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> parentElement = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;parent&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> currentChildNode = parentElement.firstChildElement;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 一直遍历子元素，直至为null</span></span><br><span class="line"><span class="keyword">while</span>( currentChildNode ) &#123;</span><br><span class="line">    <span class="comment">// 直接对元素进程操作</span></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 判断是否为最后一个元素</span></span><br><span class="line">    <span class="keyword">if</span>( currentChildNode === parentElement.lastChildElement ) &#123;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    currentChildNode = currentChildNode.nextElementSibling;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="15-3-HTML5"><a href="#15-3-HTML5" class="headerlink" title="15.3 HTML5"></a>15.3 HTML5</h3><p>HTML5代表着与以往HTML<strong>截然不同的方向</strong>；在以往的HTML中，从来<strong>没有出现过描述JavaScript接口的情形</strong>。关于JavaScript绑定的事，<strong>一律交给DOM规范去定义</strong>。</p>
<p>在HTML5规范中，包含了与<strong>标记相关</strong>的大量<strong>JavaScript API定义</strong>。</p>
<h4 id="15-3-1-CSS类拓展"><a href="#15-3-1-CSS类拓展" class="headerlink" title="15.3.1 CSS类拓展"></a>15.3.1 CSS类拓展</h4><p>自HTML4依赖，页面中最大的变化就是<strong>class属性用得越来越多</strong>。所以HTML增加了<strong>方便使用CSS类的API</strong>。</p>
<ol>
<li><p><code>getElementsByClassName()</code>方法接收一个参数：</p>
<ul>
<li>包含<strong>一个或多个类名</strong>的字符串</li>
</ul>
<p>该方法返回类名中，包含相应类的元素的<code>NodeList</code>（<em>这个<code>NodeList</code>实例是<strong>实时</strong>的</em>）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> aim = <span class="built_in">document</span>.getElemenstByClassName(<span class="string">&#x27;current active&#x27;</span>);</span><br><span class="line"><span class="comment">// 获取文档中，所有类名中，包含‘current’和‘active’的元素；</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意：必须是类名中，既有current 也有 active的元素。</p>
</blockquote>
</li>
<li><p><code>classList</code>属性</p>
<p>如果要操作类名，可以通过<code>classList</code>属性来实现添加、删除和替换；</p>
<p>由于<code>classList</code>属性是一个字符串，所以每次操作后，重新全部设值。(会显得有点麻烦)</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// &lt;div class=&quot;current active username&quot;&gt;&lt;/div&gt;</span></span><br><span class="line"><span class="comment">// 需要删除username类名</span></span><br><span class="line"><span class="keyword">let</span> targetClass = <span class="string">&#x27;username&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> classNames = div.className.split(<span class="regexp">/\s+/</span>);    <span class="comment">// 按照任何空白符号分割</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取需要删除元素的下标</span></span><br><span class="line"><span class="keyword">let</span> index = classNames.indexOf(targetClass);</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span>( index &gt; -<span class="number">1</span>) &#123;</span><br><span class="line">    classNames.splice(index,<span class="number">1</span>); <span class="comment">//删除该下标的元素</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 重新给div设置类名</span></span><br><span class="line">div.className = classNames.join(<span class="string">&quot; &quot;</span>);</span><br></pre></td></tr></table></figure>

<p>与此同时，<code>classList</code>是一个新的集合类型：<code>DOMTokenList</code>的实例，也拥有<code>length</code>、<code>item()</code>、<code>[]</code>的方法，此外还新增了如下方法：</p>
<ul>
<li>add(value)， 向类名列表中添加指定的字符串值value。 如果这个值已经存在， 则什么也不做。</li>
<li>contains(value)， 返回布尔值， 表示给定的value是否存在。</li>
<li>remove(value)， 从类名列表中删除指定的字符串值value。</li>
<li>toggle(value)， 如果类名列表中已经存在指定的value， 则删除； 如果不存在， 则添加。  </li>
</ul>
<p>显然，多了如上方法后，删除类名就方便多了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">div.remove(<span class="string">&#x27;username&#x27;</span>);</span><br></pre></td></tr></table></figure></li>
</ol>
<h4 id="15-3-2-焦点管理"><a href="#15-3-2-焦点管理" class="headerlink" title="15.3.2 焦点管理"></a>15.3.2 焦点管理</h4><p>HTML5新增了辅助DOM焦点管理的功能；</p>
<ol>
<li><code>document.activeElement</code>：始终指向当前<strong>拥有焦点的DOM元素</strong>。<ul>
<li>在页面完成加载之后，指向<code>document.body</code></li>
<li>在页面加载完成之前，指向<code>null</code></li>
</ul>
</li>
<li><code>element.hasFocus()</code>：判断是否获取了焦点<ul>
<li>返回布尔值，true代表获取了焦点</li>
</ul>
</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> button = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;myButton&#x27;</span>);</span><br><span class="line">button.focus();</span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">document</span>.activeElement === button);	<span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(button.hasFocus());		<span class="comment">// true</span></span><br></pre></td></tr></table></figure>





<h4 id="15-3-3-HTMLDocument拓展"><a href="#15-3-3-HTMLDocument拓展" class="headerlink" title="15.3. 3 HTMLDocument拓展"></a>15.3. 3 <code>HTMLDocument</code>拓展</h4><ol>
<li><p><code>document.readyState</code>属性，可能有如下两个值：</p>
<ul>
<li>loading：表示文档正在加载。</li>
<li>complete：表示文档加载完成。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>( <span class="built_in">document</span>.readyState == <span class="string">&#x27;complete&#x27;</span> )&#123;</span><br><span class="line">    <span class="comment">// do something</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>在这个属性之前，开发者通常使用<code>window.onload</code>事件处理程序设置一个标记。</p>
</blockquote>
</li>
<li><p><code>compatMode</code>属性，有如下两个值：</p>
<ul>
<li><code>CSS1Compat</code>：标准模式渲染；</li>
<li><code>BackCompat</code>：混杂模式渲染。</li>
</ul>
</li>
<li><p><code>document.head</code>属性，始终指向<code>&lt;head&gt;</code>元素。</p>
</li>
</ol>
<h4 id="15-3-4-字符集属性"><a href="#15-3-4-字符集属性" class="headerlink" title="15.3.4 字符集属性"></a>15.3.4 字符集属性</h4><p>使用<code>characterSet</code>属性，可以获取字符集属性。</p>
<h4 id="15-3-5-自定义数据属性"><a href="#15-3-5-自定义数据属性" class="headerlink" title="15.3.5 自定义数据属性"></a>15.3.5 自定义数据属性</h4><p>在HTML5中，允许<strong>自定义非标准的属性</strong>，但是需要使用前缀<code>data-</code>告诉浏览器。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">data-name</span>=<span class="string">&quot;div1&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">data-myName</span>=<span class="string">&quot;div2&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">data-my-name</span>=<span class="string">&quot;div3&quot;</span>&gt;</span></span><br><span class="line">        hello world</span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>定义了自定义数据后，可以通过元素的<code>dataset</code>属性访问；</p>
<p><code>dataset</code>时一个<code>DOMStringMap</code>实例，包含<strong>一组键值对的映射</strong>。</p>
<p><strong>可以直接通过<code>data-</code>后面的名字来访问</strong>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">&lt;div</span></span><br><span class="line"><span class="comment">        id=&quot;mydiv&quot; </span></span><br><span class="line"><span class="comment">        data-name=&quot;div1&quot;</span></span><br><span class="line"><span class="comment">        data-myName=&quot;div2&quot;</span></span><br><span class="line"><span class="comment">        data-my-name=&quot;div3&quot;&gt;</span></span><br><span class="line"><span class="comment">        hello world</span></span><br><span class="line"><span class="comment">&lt;/div&gt;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">let</span> div = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;mydiv&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(div);</span><br><span class="line"><span class="built_in">console</span>.log(div.dataset)</span><br><span class="line"><span class="built_in">console</span>.log(div.dataset.name);		<span class="comment">// div1</span></span><br><span class="line"><span class="built_in">console</span>.log(div.dataset.myname);	<span class="comment">// div2</span></span><br><span class="line"><span class="built_in">console</span>.log(div.dataset.myName);	<span class="comment">// div3</span></span><br></pre></td></tr></table></figure>

<p><em>注意：第一个除外，只要被<code>—</code>分割，开头就必需大写！</em></p>
<blockquote>
<p> 自定义数据属性非常适合需要给元素附加某些数据的场景， 比如链接追踪和在聚合应用程序中标识页面的不同部分。 另外， 单页应用程序框架也非常多地使用了自定义数据属性。  </p>
</blockquote>
<h4 id="15-3-6-插入标记"><a href="#15-3-6-插入标记" class="headerlink" title="15.3.6 插入标记"></a>15.3.6 插入标记</h4><p>DOM虽然提供了很多操作节点的API，但是一次性插入大量HTML还是比较麻烦的；</p>
<p>HTML5新增了一些插入标记，简化了其操作；</p>
<ol>
<li><p>innerHTML属性</p>
<p>在读取<code>innerHTML</code>属性时，会<strong>返回</strong>元素<strong>所有后代的HTML字符串</strong>，包括元素、注释和文本节点；</p>
<p>在写入<code>innerHTML</code>属性时，会根据提供的字符串，以新的DOM子树<strong>代替</strong>元素中的<strong>所有节点</strong>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">&lt;div id=&quot;content&quot;&gt;</span></span><br><span class="line"><span class="comment">        &lt;p&gt;This is a &lt;strong&gt;paragraph&lt;/strong&gt; with a list following it.&lt;/p&gt;</span></span><br><span class="line"><span class="comment">        &lt;ul&gt;</span></span><br><span class="line"><span class="comment">            &lt;li&gt;Item 1&lt;/li&gt;</span></span><br><span class="line"><span class="comment">            &lt;li&gt;Item 2&lt;/li&gt;</span></span><br><span class="line"><span class="comment">            &lt;li&gt;Item 3&lt;/li&gt;</span></span><br><span class="line"><span class="comment">        &lt;/ul&gt;</span></span><br><span class="line"><span class="comment">&lt;/div&gt;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">let</span> div = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;content&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(div.innerHTML);</span><br><span class="line"><span class="comment">/* 会输出如下内容</span></span><br><span class="line"><span class="comment">   &lt;p&gt;This is a &lt;strong&gt;paragraph&lt;/strong&gt; with a list following it.&lt;/p&gt;</span></span><br><span class="line"><span class="comment">   &lt;ul&gt;</span></span><br><span class="line"><span class="comment">        &lt;li&gt;Item 1&lt;/li&gt;</span></span><br><span class="line"><span class="comment">        &lt;li&gt;Item 2&lt;/li&gt;</span></span><br><span class="line"><span class="comment">        &lt;li&gt;Item 3&lt;/li&gt;</span></span><br><span class="line"><span class="comment">   &lt;/ul&gt;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">div.innerHTML = <span class="string">&#x27;&lt;p&gt;This is a &lt;strong&gt;paragraph&lt;/strong&gt; with a list following it.&lt;/p&gt;&#x27;</span></span><br><span class="line"><span class="comment">/* 会变成这样</span></span><br><span class="line"><span class="comment">&lt;div id=&quot;content&quot;&gt;</span></span><br><span class="line"><span class="comment">       &lt;p&gt;This is a &lt;strong&gt;paragraph&lt;/strong&gt; with a list following it.&lt;/p&gt;</span></span><br><span class="line"><span class="comment">&lt;/div&gt;</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>读取<code>innerHTML</code>的值，可能会因为浏览器的不同而有所不同。</p>
</blockquote>
</li>
<li><p>innerHTML的注意点：</p>
<p>在所有现代浏览器中，通过<code>innerHTML</code>插入<code>&lt;script&gt;</code>都是不会执行的；</p>
<p>在IE8及之前的版本中，通过<code>innerHTML</code>插入非可控标签（<code>&lt;script&gt;</code>、<code>&lt;style&gt;</code>、<code>注释</code>）都是不会执行的；需要在非可控标签前，添加可控标签。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">div.innerHTML = <span class="string">&quot; _ &lt;script defer&gt;&lt;\/script&gt;&quot;</span>;	<span class="comment">// 字符串充当可控标签</span></span><br><span class="line">div.innerHTML = <span class="string">&quot;&lt;div&gt;&amp;nbsp&lt;/div&gt;&lt;script defer&gt;&lt;\/script&gt;&quot;</span>; <span class="comment">// 充当可控标签</span></span><br></pre></td></tr></table></figure>

<p><em>注意：script或style都需要额外添加defer属性</em></p>
</li>
<li><p>outerHTML属性：</p>
<p>与<code>innerHTML</code>类似，但是<code>outerHTML</code>会返回<strong>包含自身在内</strong>的HTML字符串；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">&lt;div id=&quot;content&quot;&gt;</span></span><br><span class="line"><span class="comment">        &lt;p&gt;This is a &lt;strong&gt;paragraph&lt;/strong&gt; with a list following it.&lt;/p&gt;</span></span><br><span class="line"><span class="comment">        &lt;ul&gt;</span></span><br><span class="line"><span class="comment">            &lt;li&gt;Item 1&lt;/li&gt;</span></span><br><span class="line"><span class="comment">            &lt;li&gt;Item 2&lt;/li&gt;</span></span><br><span class="line"><span class="comment">            &lt;li&gt;Item 3&lt;/li&gt;</span></span><br><span class="line"><span class="comment">        &lt;/ul&gt;</span></span><br><span class="line"><span class="comment">&lt;/div&gt;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">let</span> div = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;content&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(div.innerHTML);</span><br><span class="line"><span class="comment">/* 会输出如下内容</span></span><br><span class="line"><span class="comment">&lt;div id=&quot;content&quot;&gt;</span></span><br><span class="line"><span class="comment">        &lt;p&gt;This is a &lt;strong&gt;paragraph&lt;/strong&gt; with a list following it.&lt;/p&gt;</span></span><br><span class="line"><span class="comment">        &lt;ul&gt;</span></span><br><span class="line"><span class="comment">            &lt;li&gt;Item 1&lt;/li&gt;</span></span><br><span class="line"><span class="comment">            &lt;li&gt;Item 2&lt;/li&gt;</span></span><br><span class="line"><span class="comment">            &lt;li&gt;Item 3&lt;/li&gt;</span></span><br><span class="line"><span class="comment">        &lt;/ul&gt;</span></span><br><span class="line"><span class="comment">&lt;/div&gt;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">div.innerHTML = <span class="string">&#x27;&lt;p&gt;This is a &lt;strong&gt;paragraph&lt;/strong&gt; with a list following it.&lt;/p&gt;&#x27;</span></span><br><span class="line"><span class="comment">/* 会变成这样</span></span><br><span class="line"><span class="comment">	&lt;p&gt;This is a &lt;strong&gt;paragraph&lt;/strong&gt; with a list following it.&lt;/p&gt;</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure></li>
<li><p><code>insertAdjacentHTML()</code></p>
<p>HTML5新增的方法，接收两个参数</p>
<ul>
<li>要插入标记的位置</li>
<li>插入的HTML字符串</li>
</ul>
<p>而且，第一个参数必需是如下值中的一个：</p>
<ul>
<li><code>beforebegin</code>， 插入当前元素前面， 作为前一个同胞节点；</li>
<li><code>afterbegin</code>， 插入当前元素内部， 作为新的子节点或放在第一个子节点前面；</li>
<li><code>beforeend</code>， 插入当前元素内部， 作为新的子节点或放在最后一个子节点后面；</li>
<li><code>afterend</code>， 插入当前元素后面， 作为下一个同胞节点。  </li>
</ul>
<blockquote>
<p>注意：假设为<code>&lt;p&gt;Hello World&lt;/p&gt;</code>;</p>
<p><code>beforebegin</code>中的<strong>begin</strong>指的是：<code>&lt;p&gt;</code></p>
<p><code>beforeend</code>中的<strong>end</strong>指的是：<code>&lt;/p&gt;</code></p>
</blockquote>
</li>
<li><p>其他方法</p>
<p>除了上述的三个方法外，其实还有与它们类似的三个方法，只需要把HTML替换成Text即可；</p>
<p><strong>用法与上述三个方法一致</strong>，只是传参的字符串，<strong>不会被解析为HTML，只会解析为纯文本。</strong></p>
</li>
<li><p>内存与性能问题：</p>
<p>上述介绍的方法，达到替换子节点的功能；但是会存在一定的问题：</p>
<ul>
<li>原来绑定元素引用的JavaScript对象、事件处理程序还<strong>停留在内存中</strong></li>
</ul>
<p>如果这种替换操作频繁发生，则会导致<strong>内存占用攀升</strong>；</p>
<p><strong>最好手动删除被替换元素上的关联程序、对象。</strong></p>
</li>
<li><p>跨站点脚本</p>
<p>网站攻击者，容易<strong>通过<code>innerHTML</code>注入数据</strong>，造成XSS攻击！</p>
</li>
</ol>
<h4 id="15-3-7-scrollIntoView"><a href="#15-3-7-scrollIntoView" class="headerlink" title="15.3.7 scrollIntoView()"></a>15.3.7 <code>scrollIntoView()</code></h4><p>该方法存在于<code>HTML</code>元素上，可以滚动浏览器窗口或容器元素，以便包含元素进入视口。</p>
<p>其接收如下参数：</p>
<ul>
<li><code>alignToTop</code>是一个布尔值。<ul>
<li>true： 窗口滚动后元素的顶部与视口顶部对齐。</li>
<li>false： 窗口滚动后元素的底部与视口底部对齐。</li>
</ul>
</li>
<li><code>scrollIntoViewOptions</code>是一个<strong>可选选项对象</strong>。<ul>
<li>behavior： 定义过渡动画， 可取的值为”smooth”和”auto”， 默认为”auto”。</li>
<li>block： 定义垂直方向的对齐， 可取的值为”start”、 “center”、 “end”和”nearest”， 默认为”start”。</li>
<li>inline： 定义水平方向的对齐， 可取的值为”start”、 “center”、 “end”和”nearest”， 默认为”nearest”。</li>
</ul>
</li>
<li>不传参数等同于<code>alignToTop</code>为<code>true</code>。  </li>
</ul>
<h3 id="15-4-专有拓展"><a href="#15-4-专有拓展" class="headerlink" title="15.4 专有拓展"></a>15.4 专有拓展</h3><p>尽管所有浏览器都知道遵循标准的重要性，但是不可避免的，它们也有一些<strong>专属的拓展</strong>，用于<strong>弥补自身功能的缺失</strong>。</p>
<blockquote>
<p>这里就不详细介绍了，有需要可以自行查阅。</p>
</blockquote>
<h3 id="15-5-小结"><a href="#15-5-小结" class="headerlink" title="15.5 小结"></a>15.5 小结</h3><ul>
<li>Selectors API为基于CSS选择符获取DOM元素定义了几个方法： <code>querySelector()</code>、 <code>querySelectorAll()</code>和<code>matches()</code>。</li>
<li><code>Element Traversal</code>在DOM元素上定义了额外的属性， 以方便对DOM元素进行遍历。 这个需求是因浏览器处理元素间空格的差异而产生的。</li>
<li>HTML5为标准DOM提供了大量扩展。 其中包括对<code>innerHTML</code>属性等事实标准进行了标准化， 还有焦点管理、 字符集、 滚动等特性。  </li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2022/02/28/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E5%8D%81%E4%BA%94%E7%AB%A0%EF%BC%9ADOM%E6%8B%93%E5%B1%95/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/" rel="tag">JavaScript</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
    
      <a href="/2022/02/27/JavaScript%E5%AD%A6%E4%B9%A0/%E3%80%8AJavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E3%80%8B-%20%E7%AC%AC%E5%8D%81%E5%9B%9B%E7%AB%A0%EF%BC%9ADOM/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">《JavaScript高级程序设计》- 第十四章：DOM</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "jeb2pvxjdeJQOj5OG3AUavGv-gzGzoHsz",
    app_key: "6YlB9tQJTstHMM8GOwFu4uyY",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2022
        <i class="ri-heart-fill heart_icon"></i> 子与子乘
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="欢迎"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i></p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>